package com.ecarx.module_udisk;

import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ecarx.library_base.base_fragment.BaseFragment;
import com.ecarx.library_base.base_util.ThreadUtils;
import com.ecarx.library_base.base_view.ThemeTextView;
import com.ecarx.library_base.base_widget.ConfirmDialog;
import com.ecarx.module_udisk.adapter.LogAdapter;
import com.ecarx.module_udisk.adapter.PathAdapter;
import com.ecarx.module_udisk.bean.LogBean;
import com.ecarx.module_udisk.bean.PathBean;
import com.ecarx.module_udisk.callback.FileUpdateCallback;
import com.ecarx.module_udisk.controller.FileUpdateController;

import java.util.Arrays;
import java.util.List;


public class UDiskFileFragment extends BaseFragment {

    private static final String TAG = "UDiskFileFragment";
    private final String noticePath = "usb_upgrade/file_update/uxos";
    //系统选择
    private Spinner mSpinner;
    // 日志列表
    private RecyclerView mLogRecyclerView;
    private LogAdapter mLogAdapter;
    // 文件路径列表
    private RecyclerView mPathRecyclerView;
    private PathAdapter mPathAdapter;
    //全选按钮
    private CheckBox mPathAllSelectCheckBox;
    // 安装文件选择
    private TextView tvTitleFileSelect;
    private TextView tvTitleFileSelectDetail;
    private TextView tvTitleSystemSelectDetail;
    private TextView tvTitleLog;
    private TextView tvUDiskName;
    private ThemeTextView mThemeTextView;

    private FileUpdateController mFileUpdateController;

    public UDiskFileFragment() {
        // Required empty public constructor
    }

    @Override
    protected int layoutId() {
        return R.layout.fragment_u_disk_common_update;
    }

    @Override
    protected void init(View view) {
        initView(view);
        initData();
        mFileUpdateController = new FileUpdateController(context, new FileUpdateCallback() {
            @Override
            public void fileUpdateLog(List<LogBean> logList) {
                ThreadUtils.runOnUiThread(() -> {
                    if (!isAdded()) {
                        return;
                    }
                    if (mLogAdapter != null) {
                        mLogAdapter.setLogList(logList);
                        mLogRecyclerView.scrollToPosition(mLogAdapter.getItemCount() - 1);
                    }
                });
            }

            @Override
            public void setUDiskInfo(String fsLabel) {
                ThreadUtils.runOnUiThread(() -> {
                    if (!isAdded()) {
                        return;
                    }
                    tvUDiskName.setText(fsLabel);
                });
            }

            @Override
            public void setPathBeanList(List<PathBean> pathBeanList) {
                ThreadUtils.runOnUiThread(() -> {
                    if (!isAdded()) {
                        return;
                    }
                    if (mPathAdapter != null) {
                        mPathAdapter.setPathList(pathBeanList);
                    }
                    if (pathBeanList == null) {
                        mPathAllSelectCheckBox.setChecked(false);
                    }
                });
            }

            @Override
            public void fileUpdateLogEnd() {
                ThreadUtils.runOnUiThread(() -> {
                    if (!isAdded()) {
                        return;
                    }
                    mThemeTextView.setEnabled(true);
                });
            }

            @Override
            public void pathListCheckFinish(boolean b) {
                ThreadUtils.runOnUiThread(() -> {
                    clearLoading();
                    String messageContent;
                    // 存在目标文件夹不存在情况
                    if (!b) {
                        messageContent = context.getString(R.string.file_update_notice_with_warn);
                    } else {
                        messageContent = context.getString(R.string.file_update_notice);
                    }
                    ConfirmDialog confirmDialog = new ConfirmDialog(getActivity(), messageContent, () -> {
                        mThemeTextView.setEnabled(false);
                        ThreadUtils.getCachedPool().execute(() -> {
                            if (!isAdded()) {
                                return;
                            }
                            mThemeTextView.setEnabled(false);
                            mFileUpdateController.installPathList(mPathAdapter.getCheckPathList());
                        });
                    });
                    if (!confirmDialog.isShowing()) {
                        confirmDialog.show();
                    }
                });
            }
        });
    }

    /**
     * 初始化数据
     */
    private void initData() {
        initSpinnerData();
        initUpdateLogData();
        initDiskPath();

        mThemeTextView.setOnClickListener(view -> {
            showLoading();
            ThreadUtils.getCachedPool().execute(() -> {
                mFileUpdateController.checkPathList(mPathAdapter.getCheckPathList());
            });
        });
    }

    /**
     * 初始化 U盘路径
     */
    private void initDiskPath() {
        mPathAdapter = new PathAdapter(getActivity());
        mPathRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
        mPathRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mPathRecyclerView.setAdapter(mPathAdapter);
        CompoundButton.OnCheckedChangeListener listener = (compoundButton, b) -> {
            mThemeTextView.setEnabled(b);
            mPathAdapter.setAllPathCheckStatus(b);
        };
        //设置item选中or取消选中后对全局按钮的影响
        mPathAdapter.setCallBack(new PathAdapter.recycleListStatusCallBack() {
            @Override
            public void AllPathCheckStatus(boolean b) {
                mPathAllSelectCheckBox.setOnCheckedChangeListener(null);
                mPathAllSelectCheckBox.setChecked(b);
                mPathAllSelectCheckBox.setOnCheckedChangeListener(listener);
            }

            @Override
            public void AnyPathCheckStatus(boolean b) {
                mThemeTextView.setEnabled(b);
            }
        });
        // 点击全选 or 全不选刷新 path 列表
        mPathAllSelectCheckBox.setOnCheckedChangeListener(listener);
    }

    //初始化升级日志
    private void initUpdateLogData() {
        mLogAdapter = new LogAdapter(getActivity());
        mLogRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mLogRecyclerView.setAdapter(mLogAdapter);
    }

    //初始化Spinner
    private void initSpinnerData() {
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, Arrays.asList("UX OS")) {
            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                TextView tv = (TextView) super.getView(position, convertView, parent);
                tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
                return tv;
            }
        };
        mSpinner.setAdapter(adapter);
        mSpinner.setEnabled(false);
    }

    private void initView(View view) {
        mSpinner = view.findViewById(R.id.spinner_system_choose);
        mLogRecyclerView = view.findViewById(R.id.log_recycler);
        mPathRecyclerView = view.findViewById(R.id.file_path_recycler);
        mPathAllSelectCheckBox = view.findViewById(R.id.cb_check);
        tvUDiskName = view.findViewById(R.id.title_udisk_name_detail);

        tvTitleSystemSelectDetail = view.findViewById(R.id.title_system_select_detail);
        tvTitleSystemSelectDetail.setText(R.string.file_system_select_detail);
        tvTitleLog = view.findViewById(R.id.title_log);
        tvTitleLog.setText(R.string.file_update_log);
        tvTitleFileSelect = view.findViewById(R.id.title_file_select);
        tvTitleFileSelect.setText(R.string.file_file_select);
        tvTitleFileSelectDetail = view.findViewById(R.id.title_file_select_detail);
        String title = context.getString(R.string.file_file_select_detail) + noticePath;
        tvTitleFileSelectDetail.setText(title);
        mThemeTextView = view.findViewById(R.id.btn_update);
        mThemeTextView.setText(R.string.file_start_update);
        // 初始不能点击
        mThemeTextView.setEnabled(false);
    }

}